<?php
/**
 * wecaht login class .
 * User: chan
 * Date: 2017/9/12  17:12
 */
namespace app\api\logic;

use app\api\BaseModel;
use think\Cache;
use think\Db;
use app\api\model\MemberWithdrawals as MemberWithdrawalsModel;

class Membership extends BaseModel
{
    /**
     * 记录关系
     */
    public function relation_ship()
    {
        if(!isset($this->requestData['parent_id'])){
            return array('message'=>'请传推荐人的id');
        }

        $member = db('member')->where(['id'=>$this->requestData['parent_id']])->find();
        if(empty($member))return ['message'=>'非法parent_id'];

        if($this->user['id'] == $this->requestData['parent_id'])return ['message'=>'不能推荐自己!'];

        $parent_id = db('membership')->where(['uid'=>$this->user['id']])->value('parent_id');
        $nickname = db('member')->where(['id'=>$parent_id])->value('nickname');
        if(!empty($parent_id))return ['message'=>"你已经是'{$nickname}'下线了!"];

        //不能相互推荐
        $membership_result_parent_id = db('membership')->where(['uid'=>$this->user['id'],'parent_id'=>$this->requestData['parent_id']])->find();
        $membership_result_uid_id = db('membership')->where(['parent_id'=>$this->requestData['parent_id'],'uid'=>$this->user['id']])->find();
        if(!empty($membership_result_parent_id) || !empty($membership_result_uid_id))return ['message'=>'不能相互推荐!'];

        $date['parent_id'] = $this->requestData['parent_id'];
        $date['uid'] = $this->user['id'];
        $date['creatime'] = time();

        //关系记录添加
        $membership = db('membership')->insert($date);
        if(!$membership)return ['message'=>'推荐失败!'];

        $membership_recording = db('membership_recording')->where(['uid'=>$this->requestData['parent_id']])->find();

        $recording['creatime'] = time();

        if(empty($membership_recording)){
            $recording['uid'] = $this->requestData['parent_id'];
            $recording['next_home'] = $this->user['id'];
            db('membership_recording')->insert($recording);
        }else{  
            $next_home = explode(",", $membership_recording['next_home']);
            $next_home[]=$this->user['id'];;
            $recording['next_home'] = implode(",", $next_home);
            db('membership_recording')->where(['uid'=>$this->requestData['parent_id']])->update($recording);
        }
    }

    /**
     * 二维码页面
     */
    public function qr_code()
    {
        $result = [];
        $qr_code = $this->makeQr($this->user['id']);
        $status = db('member_apply')->where(['uid'=>$this->user['id']])->value('status');
        if($status != '1')return ['message'=>'你还不是会员!'];
        $result['code'] = __ROOT__.'/static/'.$qr_code;
        return $result;
    }

    /**
    *   二维码路径
    */
    public function Wechatcode($user_id){
        $result =  new \app\api\logic\Wechatcode();
        $result = $result->get_relationship($user_id);
        return $result;
    }

    /**
     * 生成二维码
     */
    public function makeQr($user_id){
        //生成二维码图片
        $img_path_binary = $this->Wechatcode($user_id);
        $img_name = md5($img_path_binary);

        $this->checkPath('./static/code');

        $file = fopen('./static/code/'.$img_name.".png","w");//打开文件准备写入
        fwrite($file,$img_path_binary);//写入
        fclose($file);//关闭
        
        return 'code/'.$img_name.".png";
    }

    /**
     * 检查目录是否可写
     * @param  string   $path    目录
     * @return boolean
     */
    protected function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }
        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            return false;
        }
    }

    /**
    *  我的会员
    *
    */
    public function my_member(){
        $page = isset($this->requestData['page'])?$this->requestData['page']:'1';
        $next_home = db('membership_recording')->where(['uid'=>$this->user['id']])->value('next_home');

        $result = [];
        if(!empty($next_home)){
            $next_home = explode(',', $next_home);
            $next_home_count = count($next_home);
        }else{
            $next_home_count = 0;
        }
        $result['member_count'] = $next_home_count;

        $member = db('member')->where(['id'=>['in',$next_home]])->field('headimage,nickname')->page("{$page},10")->select();
        $result['member'] = $member;

        return $result;
    }

    /**
    *绑定银行卡
    */
    public function my_bankcard(){
        (new \app\api\validate\System())->bindcard();
        $is_edit = isset($this->requestData['is_edit'])?$this->requestData['is_edit']:'0';
        
        $db_bankcard = db("member_bankcard");
        $code = trim($this->requestData['code']);
        if (base64_encode($code) != Cache::get($this->requestData['mobile'])) {
            return array('message'=>'验证码错误');
        }
        $data = [
            'name' =>$this->requestData['name'],
            'card_num' => $this->requestData['card_num'],
            'bank' => $this->requestData['bank'],
            'mobile' =>$this->requestData['mobile'],
            "uid"=>  $this->user['id'],
        ];
        $card=$db_bankcard->where(['uid'=>$this->user['id']])->find();

        if($is_edit != '1'){
            if($card) return array("message"=>'无需重复绑定');
            $res=$db_bankcard->insert($data);
        }else{
            $res=$db_bankcard->where(['uid'=>$this->user['id']])->update($data);
        }

        if(!$res) return array("message"=>'绑定失败');
    }

    /**
    *用户中心
    */
    public function balance(){
        $result = [];

        $user_balance = (new MemberWithdrawalsModel())->getUserBalance($this->user['id']);

        $result['user_balance'] = $user_balance;

        //是否绑定银行卡
        $member_bankcard = db('member_bankcard')->where(['uid'=>$this->user['id']])->find();

        if(!empty($member_bankcard)){
            $result['is_binding'] = 1;          //绑定
        }else{
            $result['is_binding'] = 0;          //取消绑定
        }

        $result['bankcard_info'] = $member_bankcard;

        return $result;
    }

    //提现
    public function withdraw(){
        (new \app\api\validate\System())->apply();
        
        $db_withdrawals = db("member_withdrawals");
        
        $user_balance = (new MemberWithdrawalsModel())->getUserBalance($this->user['id']);

        $config=db("config")->where("id=5")->find();
        $poundage=round(floatval($config['value'])*$this->requestData['money']/100,2);

        $db_bankcard = db("member_bankcard");
        $card=$db_bankcard->where(['uid'=>$this->user['id']])->find();
        $code = isset($this->requestData['code'])?$this->requestData['code']:'';
        $code = trim($code);
        if(empty($code))return ['message'=>'验证码为空!'];
        if (base64_encode($code) != Cache::get($card['mobile'])) {
            return array('message'=>'验证码错误');
        }

        if(floatval($this->requestData['money'])<=0) return array("message"=>'提现金额有误');
        if($user_balance<floatval($this->requestData['money'])) return array("message"=>'余额不足');
        if(empty($card))return array("message"=>'请填写银行卡信息才能提现!');

        $data = [
            'uid' => $this->user['id'],
            'money' =>$this->requestData['money'],
            'poundage' =>$poundage,
            'paid' => $this->requestData['money']-$poundage,
            'create_time' =>TIMESTAMP,
            "name"=> $card['name'],
            "card_num"=>$card['card_num'],
            "mobile"=>$card['mobile'],
            "bank"=>$card['bank']
        ];
        try{
            $res=$db_withdrawals->insert($data);
            if(!$res) throw new \Exception('提现失败');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array("message"=>$e->getMessage());
        }
    }

    /**
    * 个人明细
    */
    public function personal_details(){
        $uid= $this->user['id'];
        $page = isset($this->requestData["page"])?$this->requestData["page"]:'1';

        $next_home = db('membership_recording')->where(['uid'=>$uid])->value('next_home');

        $next_home = explode(',', $next_home);

        $member_balance = db('member_balance')->alias('mb')->join('order o','o.id=mb.order_id')->where(['o.user_id'=>['in',$next_home]])->page("{$page},10")->field("mb.*,o.total_price")->select();

        foreach ($member_balance as $key => $value) {
            $member = db('member')->where(['id'=>$value['uid']])->field('headimage,nickname')->find();
            $member_balance[$key]['headimage'] = $member['headimage'];
            $member_balance[$key]['nickname'] = $member['nickname'];
        }

        return $member_balance;
    }

    //申请会员
    public function apply_for_membership(){
        if(!isset($this->requestData["mobile"]))return ['message'=>'请传申请人电话!'];
        if(!isset($this->requestData["code"]))return ['message'=>'请传验证码!'];
        $mobile = $this->requestData["mobile"];
        $user = $this->user['id'];
        $member_apply = db('member_apply')->where(['uid'=>$user])->find();
        if(!empty($member_apply))return ['message'=>'已申请过了!'];

        $code = trim($this->requestData['code']);
        if (base64_encode($code) != Cache::get($mobile)) {
            return array('message'=>'验证码错误');
        }

        $data['mobile'] = $mobile;
        $data['uid'] = $user;

        db('member_apply')->insert($data);
    }

    //查询申请会员
    public function inquire_member(){

        $user = $this->user['id'];
        $member_apply = db('member_apply')->where(['uid'=>$user])->find();

        return $member_apply;
    }
}